using System;
using System.Web;
using System.Web.Caching;
using System.Text;

namespace ECCIT.Data
{
    /// <summary>
	/// 
	/// </summary>
	public class DataCache
	{
        protected HttpRuntime _oRunTimeHTTP = null;

        public Cache Cache
        {
            get
            {
                lock (this)
                {
                    if (this._oRunTimeHTTP == null)
                    {
                        _oRunTimeHTTP = new HttpRuntime ();
                    }
                }

                return HttpRuntime.Cache;
            }
        }

		private const string SqlDataBaseCacheKey = "SqlDataBaseCache-{0}";
        private static Cache InnerCache = CreateCacheInstance ();

        private static Cache CreateCacheInstance ()
        {
            DataCache cache = new DataCache ();
            return cache.Cache;
        }

		public static string GetDependencyKey(string[] tableNameArray)
		{
			StringBuilder builder = new StringBuilder();

			int length = tableNameArray.Length;
			int i = 0;
			foreach(string tableName in tableNameArray)
			{				
				builder.Append(string.Format(SqlDataBaseCacheKey, tableName));

				if( i < length-1 )
					builder.Append(",");

				i++;
			}

			string cacheKey = builder.ToString();

			return cacheKey;
		}

		public static object GetValue(string cacheKey)
		{
			return InnerCache[cacheKey];
		}

		public static string InsertCache(string[] tableNameArray, string key, object value) 
		{
			string dbKey = CreateTableDependency(tableNameArray);

			// Create key dependency
			string[] s = new string[] {dbKey};
			CacheDependency d = new CacheDependency(null, s);

			// do the actual insert
			if( InnerCache[key] == null )
				InnerCache.Insert(key, value, d);

			return dbKey;
		}

		private static int GetTableKey (string tableNameList) 
		{
			string cmdSelect = "SELECT ChangeID FROM ChangeNotification WHERE TableName = '" + tableNameList + "'";
			int changeID = -1;

			object obj = DBHelper.ExecuteScalar(cmdSelect);
			if( obj != null && obj != DBNull.Value )
			{
				changeID = int.Parse(obj.ToString());
			}
			else
			{
				string cmdInsert = "INSERT INTO ChangeNotification VALUES('" + tableNameList + "',-1);";
				DBHelper.ExecuteNonQuery(cmdInsert);
			}

			return changeID;
		}

		private static string CreateTableDependency (string[] tableNameArray) 
		{
			string dbKey = GetDependencyKey(tableNameArray);
            string tableNameList = new JoinedString(tableNameArray, ",").ToString();

			if ( InnerCache[dbKey] != null)
				return dbKey;

			// Add table entry into the cache
			if ( InnerCache[dbKey] == null ) 
				InnerCache.Insert(dbKey, GetTableKey(tableNameList));

			return dbKey;
		}
	}
}
